<template>
  <view class="flex-column-box">
    <view v-html="qrcodeHtml"></view>
    <view class="flex-item">
      <text class="flex-item-title">
        内容
      </text>
      <input class="flex-item-input" ref="qrcodeInput" v-model="qrcodeText"/>
    </view>

    <view class="button" @click="genQrcode(qrcodeText,true)">
      生成二维码
    </view>
  </view>
</template>

<script>

import QRCode from 'qrcode';

export default {
  data() {
    return {
      qrcodeText: "",
      qrcodeHtml: ""
    }
  },
  mounted() {
    this.genQrcode("Hello World", false)
    // 聚焦到input到
    console.log(this.$refs.qrcodeInput)
  },
  methods: {

    genQrcode(qrCodeText, showLoading) {
      if (showLoading) {
        uni.showLoading({
          title: "生成中..."
        })
      }
      try {
        // 生成二维码图片的选项
        const options = {
          errorCorrectionLevel: 'H',
          type: 'image/png',
          rendererOpts: {
            quality: 0.3,
          },
        };

        const qrcode = QRCode.toDataURL(qrCodeText ? qrCodeText : this.qrcodeText, (err, url) => {
          if (err) {
            console.error(err);
            return;
          }
          this.qrcodeHtml = `<img src="${url}" alt="QR Code" style="width: 260px;height: 260px;" /">`;
        });
      } finally {
        if (showLoading) {
          uni.hideLoading()
          uni.showToast({
            title: "生成成功",
            icon: "success",
            duration: 2000
          })
        }
      }

    }
  }
}
</script>

<style scoped lang="scss">

.flex-column-box {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  padding-top: 50px;

  .flex-item {
    width: 100%;
    background-color: white;;
    height: 50px;
    display: flex;
    align-items: center;
    padding-left: 30px;
    margin-top: 20px;

    text {
      font-size: 40rpx;
      margin-right: 30px;
    }
  }

  .button {
    margin-top: 20px;
    width: 90%;
    background: #3677f0;
    border-radius: 10rpx;
    height: 40px;

    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;

    // 字体颜色白色, 大小30rpx
    color: white;
    font-size: 40rpx;
  }
}

</style>
